package com.gin.kotlin.no_gay_alliance.fragment.main

import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.core.view.MenuProvider
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.ForumSearchActivity
import com.gin.kotlin.no_gay_alliance.base.FragmentStateContainer
import com.gin.kotlin.no_gay_alliance.callback.SCallback
import com.gin.kotlin.no_gay_alliance.fragment.main.community.MainFavorForumFragment
import com.gin.kotlin.no_gay_alliance.fragment.main.community.MainForumEntryGroupFragment
import com.gin.kotlin.no_gay_alliance.model.ForumSubGroupModel
import com.gin.kotlin.no_gay_alliance.provider.ngajs.IndexForumsProvider
import com.gin.nga.response.resource.index.ForumGroup
import java.io.IOException

/**
 * * 首页 - 社区
 * * 包含功能：版面搜索，收藏版面，首页版面入口
 */
class MainCommunityFragment : AbstractMainTabFragment(), MenuProvider, SCallback<List<ForumGroup>> {
    private lateinit var forums: MutableList<FragmentStateContainer>

    override fun obtainFragmentStateContainers() = mutableListOf(
        FragmentStateContainer("收藏版面") { MainFavorForumFragment() },
    ).also { this.forums = it }

    override fun onCreateView2() {
        request()
    }

    /**
     * 添加菜单项
     * @param menu Menu
     * @param menuInflater MenuInflater
     */
    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.search, menu)
    }

    /**
     * 处理菜单项点击
     */
    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            R.id.mi_search -> {
                ForumSearchActivity.start(requireContext())
                true
            }

            else -> false
        }
    }

    private fun request(ignoreCache: Boolean = false) = IndexForumsProvider.getInstance().enqueue(ignoreCache, this)

    override fun onSuccess(data: List<ForumGroup>) {
        data.map {
            val groups = it.subGroups?.map { g -> ForumSubGroupModel(g) }?.let { l -> ArrayList(l) }
            FragmentStateContainer(it.name) { MainForumEntryGroupFragment.newInstance(groups) }
        }.forEach { this.forums.add(it) }

        this.b?.viewPager2?.adapter?.notifyItemRangeInserted(1, data.size)
    }

    override fun onFailure(call: okhttp3.Call, e: IOException) {
        toast("首页版面入口请求失败")
        Log.e(TAG, "首页版面入口请求失败", e)
    }
}